from flask import Blueprint, jsonify, request
from app.services.traffic_service import TrafficService
from app.config import BAIDU_MAP_CONFIG

traffic_bp = Blueprint('traffic', __name__)

# 获取拥堵等级
def get_congestion_type(status):
    """根据拥堵指数返回拥堵等级"""
    if status <= 2:
        return 'success'
    elif status <= 4:
        return 'warning'
    else:
        return 'danger'

# 聚合多个区域的交通数据
def aggregate_traffic_data(responses):
    """聚合多个区域的交通数据"""
    total_status = 0
    total_areas = 0
    descriptions = []
    road_traffic_data = []
    
    for data in responses:
        if data.get('status') == 0:
            if 'evaluation' in data:
                total_status += data['evaluation']['status']
                total_areas += 1
            if 'description' in data:
                descriptions.append(data['description'])
            if 'road_traffic' in data:
                road_traffic_data.extend(data['road_traffic'])
    
    if total_areas == 0:
        return None
    
    avg_status = total_status / total_areas
    all_descriptions = ' '.join(descriptions)
    
    # 对道路数据去重
    unique_roads = {}
    for road in road_traffic_data:
        road_name = road.get('road_name')
        if road_name and road_name != 'UNKNOW':
            if 'congestion_sections' in road:
                if road_name not in unique_roads:
                    unique_roads[road_name] = road
                else:
                    existing_sections = unique_roads[road_name].get('congestion_sections', [])
                    new_sections = road.get('congestion_sections', [])
                    unique_roads[road_name]['congestion_sections'] = existing_sections + new_sections
    
    return {
        'status': avg_status,
        'description': all_descriptions,
        'road_traffic': list(unique_roads.values())
    }

@traffic_bp.route('/api/traffic/congestion', methods=['GET'])
def get_congestion_data():
    try:
        bounds = BAIDU_MAP_CONFIG['bounds']
        bounds_list = BaiduMapService.generate_grid_bounds(
            bounds['min_lat'],
            bounds['max_lat'],
            bounds['min_lng'],
            bounds['max_lng']
        )
        
        all_responses = TrafficService.get_congestion_data(bounds_list)
        aggregated_data = aggregate_traffic_data(all_responses)
        
        if not aggregated_data:
            raise Exception('未能获取有效的交通数据')
        
        congestion_level = {
            'value': round(aggregated_data['status'], 1),
            'text': aggregated_data['description'],
            'type': get_congestion_type(aggregated_data['status']),
            'road_traffic': aggregated_data['road_traffic']
        }

        return jsonify({
            'success': True,
            'data': congestion_level
        })

    except Exception as e:
        print("Error:", str(e))
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@traffic_bp.route('/api/traffic/time-distribution', methods=['GET'])
def get_time_distribution():
    try:
        data_type = request.args.get('dataType', '1')  # 默认为拥堵延时指数
        data = TrafficService.get_time_distribution(data_type)
        
        return jsonify({
            'success': True,
            'data': data
        })

    except Exception as e:
        print("Error fetching time distribution:", str(e))
        return jsonify({
            'success': False,
            'message': '获取时段数据失败'
        }), 500

@traffic_bp.route('/api/traffic/district-rank', methods=['GET'])
def get_district_rank():
    """获取区域排名数据"""
    try:
        links_type = request.args.get('type', '1')  # 默认获取区域拥堵排名
        if links_type not in ['1', '3', '4']:
            return jsonify({
                'success': False,
                'message': '无效的排名类型'
            }), 400
            
        result = TrafficService.get_district_rank(links_type)
        if not result['success']:
            return jsonify(result), 500
            
        return jsonify(result)
        
    except Exception as e:
        print("Error fetching district rank:", str(e))
        return jsonify({
            'success': False,
            'message': '获取区域排名数据失败'
        }), 500

@traffic_bp.route('/api/traffic/indicators', methods=['GET'])
def get_traffic_indicators():
    """获取交通指标数据"""
    try:
        result = TrafficService.get_traffic_indicators()
        if not result['success']:
            return jsonify(result), 500
            
        return jsonify(result)
        
    except Exception as e:
        print("Error fetching traffic indicators:", str(e))
        return jsonify({
            'success': False,
            'message': '获取交通指标数据失败'
        }), 500 